<script setup lang="ts">
import type { NetworkListProps, NetworkProps } from '@/types';

import {
  type ComponentInternalInstance,
  getCurrentInstance,
  nextTick,
  onMounted,
  ref,
  watch,
} from 'vue';

import { useNetwork } from '@vueuse/core';
import { ElBadge, ElMessage } from 'element-plus';
import { customAlphabet } from 'nanoid';

// import { useAppStore } from '@/store';

defineOptions({
  name: 'SystemNetwork',
});

const nanoid = customAlphabet('abcdefghijklmnopqrstuvwxyz', 10);
const { isOnline } = useNetwork();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const baseUrl = proxy?.$config.baseUrl;
// const appStore = useAppStore();
// const handleNetworkConfig = () => {
//   appStore.openAppByKey('system_network_config');
// };
const loading = ref(false);
const list = ref<NetworkListProps>();
const currentKey = ref<string>();
const currentNetwork = ref<NetworkProps[]>();

function truncateText() {
  const containers = document.querySelectorAll('.network-title');
  containers.forEach((container: Element) => {
    const text = container.textContent || '';

    if (text.length >= 24) {
      const newText = `${text.slice(0, 10)}...${text.slice(-10)}`;
      container.textContent = newText;
    }
  });
}

const loadNetworkInfo = () => {
  loading.value = true;
  try {
    const url = `${baseUrl}/network/info`;
    fetch(url, {
      method: 'GET',
    })
      .then((response) => response.json())
      .then((res) => {
        const { code, data, msg } = res;
        if (code === 200) {
          list.value = data;
          currentKey.value = Object.keys(data)[0];
          nextTick(() => {
            truncateText();
          });
        } else {
          ElMessage.error(msg || '获取文件夹目录失败');
        }
      });
  } catch (error) {
    console.log(error);
    ElMessage.error('请求发生了错误，请稍后重试');
  } finally {
    loading.value = false;
  }
};
watch(
  () => currentKey.value,
  (val) => {
    currentNetwork.value = [];
    if (list.value && val) {
      currentNetwork.value = (list.value[val] as NetworkProps[]).reverse();
    }
  },
);
onMounted(() => {
  loadNetworkInfo();
});
</script>

<template>
  <div class="wos-network">
    <div class="wos-network__left">
      <template v-for="item in Object.keys(list || {})" :key="item">
        <div
          :class="[{ check: currentKey === item }]"
          :title="item"
          class="network-title"
          @click="currentKey = item"
        >
          {{ item }}
        </div>
      </template>
    </div>
    <div class="wos-network__right">
      <div class="card">
        <div class="content">
          <div class="label">net</div>
          <div class="desc">
            <ElBadge
              :type="isOnline ? 'success' : 'danger'"
              class="mr-2 mt-2"
              is-dot
            />
            {{ currentKey }}
          </div>
        </div>
      </div>
      <template
        v-for="item in currentNetwork"
        :key="`${item.family}_${nanoid()}`"
      >
        {{ item.family }}
        <div class="card">
          <template
            v-for="key in Object.keys(item)"
            :key="`${key}_${nanoid()}`"
          >
            <div class="content">
              <div class="label">{{ key }}</div>
              <div class="desc">{{ item[key as keyof NetworkProps] }}</div>
            </div>
          </template>
        </div>
      </template>
      <!-- <div class="footer">
        <ElButton size="small" type="primary" @click="handleNetworkConfig">
          详细信息...
        </ElButton>
      </div> -->
    </div>
  </div>
</template>
<style lang="scss">
@import url('./css/network.scss');
</style>
